package com.smile.config;

//import cn.hutool.core.bean.BeanUtil;
//import com.smile.commons.page.R;
import cn.hutool.core.bean.BeanUtil;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 动态路由配置
 *
 * @author 苦瓜不苦
 * @date 2022/11/13 23:26
 **/
@Slf4j
@RestController
@RequestMapping("/route")
public class GatewayRouteConfig implements ApplicationEventPublisherAware {
    public final Map<String, RouteDefinitionObject> MAP = new ConcurrentHashMap<>();
    private final RouteDefinitionWriter routeDefinitionWriter;
    private ApplicationEventPublisher applicationEventPublisher;

    public GatewayRouteConfig(RouteDefinitionWriter routeDefinitionWriter) {
        this.routeDefinitionWriter = routeDefinitionWriter;
    }

    @Override
    public void setApplicationEventPublisher(@NonNull ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    /**
     * 新增路由
     * {"filters":[{"name":"StripPrefix","args":{"_genkey_0":"2"}}],"id":"item-system","uri":"lb://item-system","order":0,"predicates":[{"name":"Path","args":{"_genkey_0":"/api/system/**"}}]}
     */
    @PostMapping("/save")
    public R<String> save(@RequestBody RouteDefinitionObject routeDefinitionObject) {
        try {
            // 路由模型转换成路由对象
            RouteDefinition definition = BeanUtil.toBean(routeDefinitionObject, RouteDefinition.class);
            URI uri = routeDefinitionObject.getUri().startsWith("http")
                    ? UriComponentsBuilder.fromHttpUrl(routeDefinitionObject.getUri()).build().toUri()
                    : URI.create(routeDefinitionObject.getUri());
            definition.setUri(uri);
            // 新增
            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
            MAP.put(routeDefinitionObject.getId(), routeDefinitionObject);
            return R.ok();
        } catch (Exception e) {
            log.error("\n", e);
        }
        return R.fail();
    }

    /**
     * 删除路由
     */
    @GetMapping("/delete")
    public R<Mono<ResponseEntity<Object>>> delete(@RequestParam("id") String id) {
        try {
            Mono<ResponseEntity<Object>> responseEntityMono = routeDefinitionWriter.delete(Mono.just(id))
                    .then(Mono.defer(() ->
                            Mono.just(ResponseEntity.ok().build())
                    )).onErrorResume((t) ->
                                    t instanceof NotFoundException
                            , (t) ->
                                    Mono.just(ResponseEntity.notFound().build())
                    );
            MAP.remove(id);
            return R.ok(responseEntityMono);
        } catch (Exception e) {
            log.error("\n", e);
        }
        return R.fail();
    }

    /**
     * 更新路由
     * {"filters":[{"name":"StripPrefix","args":{"_genkey_0":"2"}}],"id":"item-system","uri":"lb://item-system","order":0,"predicates":[{"name":"Path","args":{"_genkey_0":"/api/system/**"}}]}
     */
    @PostMapping("/update")
    public R<String> update(@RequestBody RouteDefinitionObject routeDefinitionObject) {
        try {
            // 删除
            delete(routeDefinitionObject.getId());
            // 新增
            save(routeDefinitionObject);
            return R.ok();
        } catch (Exception e) {
            log.error("\n", e);
        }
        return R.fail();
    }

    /**
     * 查询路由
     */
    @GetMapping("/list")
    public R<Collection<RouteDefinitionObject>> list() {
        return R.ok(MAP.values());
    }
}